package com.lanhai.agv.dispatch;

import com.lanhai.agv.cache.AgvCache;
import com.lanhai.agv.cache.AgvItem; 
import com.lanhai.agv.cache.ParkCache;
import com.lanhai.agv.cache.ParkItem;
import com.lanhai.agv.log.LogData;
import com.lanhai.agv.log.LogQueue; 
import com.lanhai.agv.queue.DispatchQueue;
import com.lanhai.agv.queue.DispatchUnit;
import com.lanhai.agv.queue.StationEventUnit;
import com.lanhai.agv.queue.TargetCmdEnum;
import com.lanhai.agv.thirdpart.StationData;
import com.lanhai.agv.thirdpart.StationInterface;
import com.lanhai.agv.thirdpart.StationResolveFactory;

/**
 * 对接设备指令处理
 * 
 * @author virus408
 *
 */
public class StationResolve {
	public static void Resolve(StationEventUnit unit) {
		// 先拿停泊点
		ParkItem park = ParkCache.getParkByStation(unit.getIp(), unit.getPort());
		if (park == null)
			return;

		// 解析到的对象
		StationInterface station = StationResolveFactory.getStationResolve(park.getCmdSign());
		if (station == null)
			return;

		StationData sdata = station.resoleveData(unit.getData());
		if (sdata == null)
			return;

		switch (sdata.getEventType()) {
		case AllowLeave: 	
			Log(sdata,unit.getIp());
			// 通知小车离开
			AgvItem agv = AgvCache.getAgvByPark(park.getParkNo() );
			
			 if(agv!=null) {
					//更新小车下道工序
						AgvCache.updateAgvNextProcess(agv.getAgvId() , park.getNextprocess()); 
				 }
			 
			 
		    //回退主路
			AgvResolve.AgvToRoad(agv, 0);
			 
			break;
		case AllowTrans:
			 	
			Log(sdata,unit.getIp());
			// 通知调度传输
			DispatchUnit du = new DispatchUnit();
			du.setFromAgv(false);
			du.setIp(unit.getIp());
			du.setPort(unit.getPort());
			du.setTarget(TargetCmdEnum.Judgement);
			DispatchQueue.Push(du); 
			break;
		case Error:
			break;
		case HasGift:
			// 更新装卸情况 
			 ParkCache.updateStationMount(unit.getIp(), unit.getPort(), sdata.isNeedIn(),
					sdata.isNeedOut(),sdata.getInNum(),sdata.getOutNum());
		 
			 Log(sdata,unit.getIp());
			 
			break;
		default:
			break;

		}

	}
	
	/**
	 * 生成日志并写进队列里
	 * @param data
	 * @param ip
	 */
	static void Log(StationData data,String ip) {
		LogData logobj=LogData.fromStation(data, ip);
		LogQueue.Push(logobj);
	}
}
